package com.zilue.hfqueue.queue.block;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created by ZD on 2017/5/4.
 */
public class HFQueueWriteBlock {
    private final int FILE_MAX_SIZE = 1024 * 1024 * 32;
    private final int INT_SIZE = 4;
    private final String MODE = "rw";
    private RandomAccessFile file;
    private MappedByteBuffer buffer;
    private final String POSTFIX = ".block";
    private int block_num;

    public HFQueueWriteBlock(final String path, final String toipc, int blockNum, int index) throws IOException {
        block_num = blockNum;
        file = new RandomAccessFile(path + "HFQueue_" + toipc + "_" + block_num + POSTFIX, "rw");
        if (FILE_MAX_SIZE != file.length()) {
            file.setLength(FILE_MAX_SIZE);
        }
        buffer = file.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, file.length()).force();
        buffer.position(index);
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    buffer.force();
                    if (file != null)
                        file.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }));
    }


    public int writeData(byte[] bytes) throws UnsupportedEncodingException {
        int length = bytes.length;
        if (length + INT_SIZE + buffer.position() > FILE_MAX_SIZE)
            return -1;
        buffer.putInt(length);
        buffer.put(bytes);
        return buffer.position();
    }

    public void close() {
        try {
            buffer.force();
            if (file != null)
                file.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


}
